package com.sojson.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Before;

import com.google.common.util.concurrent.RateLimiter;
import com.sojson.annotation.aspect.PointcutsWebBase;
import com.sojson.config.exception.TransErrorCode;
import com.sojson.config.exception.TransException;

/**
 * 限流切面
 * 
 * @author liu
 * @date 2021-08-16
 */
// @Aspect
// @Component
public class CurrentLimitingAspect extends PointcutsWebBase {

    /** 每秒只发出5个令牌,实际发放的令牌为5+1,6枚 */
    RateLimiter rateLimiter = RateLimiter.create(5.0);

    /**
     * 请求处理之前
     * 
     * @param jp 切点
     * @throws Throwable
     */
    @Before(POINTCUT_CONTROLLER)
    public void before(JoinPoint jp) throws Throwable {
        boolean tryAcquire = rateLimiter.tryAcquire();
        if (!tryAcquire) {
            throw new TransException(TransErrorCode.THREAD_BUSY);
        }
    }

}